import React, { Component } from 'react';
import moment from 'moment'
import { connect } from 'react-redux'  
import { Modal, Form, Input,Select ,DatePicker,message,TimePicker,Radio,Button,Row, Col,TreeSelect} from 'antd';

const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option =Select.Option;
var dayList = ['1', '2','3', '4','5', '6','7', '8','9', '10','11', '12','13', '14','15', '16','17', '18','19', '20','21', '22','23', '24','25', '26','27', '28','29', '30','31'];

class AddInventoryModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  okHandler = () => {
     const { onOk,cycletime } = this.props;
     this.props.form.validateFields((err, values) => {
      if (!err) {
        var list = [];
        cycletime.inventoryTimes.map(d=>{
          var dr = {
            ...d,
          };
          if(dr.startTime){
            dr.startTime = new moment(dr.startTime).format("HH:mm");
            list.push(dr);
          }  
        })
        if(list!=null&&list.length>0){
            values = {
              ...values,
              cycleType:cycletime.cycleType,
              inventoryTimes: list,
            }
            onOk(values);
        }else{
            message.error('请选择盘点时间');
        }
      }
     });
  };
 
  onRadioChange = (e) => {
    const { onRadioChange } = this.props;
    onRadioChange(e.target.value);
  }; 
  handleRoomChange = (value) => {
    const { handleRoomChange } = this.props;
    handleRoomChange(value);
  }; 
  
  
  render() {
    const { children, dispatch,item,roomList,userList,isShowUser,rackList,editDetailHandler,addDetailHandler,cycletime} = this.props;  
    const { getFieldDecorator } = this.props.form;   
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };  
    const formItemLayout1 = {
      labelCol: { span: 3 },
      wrapperCol: { span: 19 },
    };  
   
    const getDay = data => data.map((item) => {
      return <Option key={item+''}>{item}日</Option>
     })
     const cycletimeChange = function(e){
       dispatch({
         type: "inventory/upState",
         payload: {
           cycletime: {
            inventoryTimes: [],
             cycleType: e.target.value,
           }
         }
       })
     }
     const addIns = () => {
       cycletime.inventoryTimes.push({})
       dispatch({
         type: "inventory/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const delIns = (ind) => {
       cycletime.inventoryTimes.splice(ind,1);
       dispatch({
         type: "inventory/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const changeIns = (value,ind,name) => {
       //console.log(value)
       // console.log(name)
       cycletime.inventoryTimes[ind][name] = value;
       dispatch({
         type: "inventory/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const showIns = data => {
       switch(data.cycleType){
         case 1:
          return data.inventoryTimes.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
                <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
         case 2:
          return data.inventoryTimes.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
               <Select value={item.day!=null?item.day+'':undefined} placeholder="选择时间" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 60 }} >
                 <Option value="1">周一</Option>
                 <Option value="2">周二</Option>
                 <Option value="3">周三</Option>
                 <Option value="4">周四</Option>
                 <Option value="5">周五</Option>
                 <Option value="6">周六</Option>
                 <Option value="7">周日</Option>
               </Select> 
             </div>
             <div style={{float:"left",marginRight:30}}>
                <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
         case 3:
          return data.inventoryTimes.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
               <Select value={item.day!=null?item.day+'':undefined} placeholder="选择日期" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 60 }} >        
                  {getDay(dayList)}                       
               </Select>
             </div>
             <div style={{float:"left",marginRight:20}}>
               <TimePicker format="HH:mm" value={item.startTime} onChange={(e)=>changeIns(e,index,"startTime")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
       }
     }

    const getRoom = data => data.map((item) => {
     return <Option key={item.id_+''}>{item.name}</Option>
    }) 
    const getUser = data => data.map((item) => {
     return <Option key={item.id_+''}>{item.name}</Option>
    })
 
    const treeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id+'';
        d.value = d.id+'';
        d.children = d.rackList && d.rackList.length > 0 ? treeData(d.rackList) : [];
        return d;
      })
    }

    return (
      <span>
            <Modal
                    maskClosable= {this.props.maskClosable}
                    confirmLoading= {this.props.confirmLoading}
                    title={this.props.title}
                    width={700}
                    visible={this.props.visible}
                    onOk={this.okHandler}
                    onCancel={this.props.onCancel}
                    key={this.props.newKey}
            >
         
                <Form layout='horizontal' onSubmit={this.okHandler}>
                      <FormItem style={{marginBottom:'0px'}}>
                        {getFieldDecorator('id',{initialValue:item.id_})(
                          <Input type="hidden"/>
                        )}
                      </FormItem> 
                      <Row>
                        <Col span={12}>
                          <FormItem
                              {...formItemLayout}
                                label="计划名称"
                                hasFeedback
                              >
                              {
                                getFieldDecorator('inventoryName', {
                                  initialValue: item.inventoryName,
                                  rules: [{
                                    required: true, whitespace: true, message: '请输入计划名称',
                                  },{
                                    max:20,message: '主题不能超过20个字',
                                  }]
                                })(<Input  placeholder="请输入计划名称" />)
                              }
                          </FormItem>  
                        </Col>
                        <Col span={12}>
                          <FormItem
                              {...formItemLayout}
                                label="盘点类型"
                                hasFeedback
                              >
                              {getFieldDecorator('inventoryType', {
                                initialValue:  item.inventoryType == null? 2 : item.inventoryType,                            
                              })(
                                <RadioGroup onChange={this.onRadioChange}>                                
                                  <Radio value={2}>手动盘点</Radio>
                                  <Radio value={1}>自动盘点</Radio>
                                </RadioGroup>
                                )}
                          </FormItem>                      
                        </Col>
                      </Row>
                      <Row>
                        <Col span={12}>
                          {isShowUser==2?(<FormItem
                              {...formItemLayout}
                                label="盘点人"
                                hasFeedback
                              >
                              {getFieldDecorator('operatiorBy', {
                                  initialValue: item.operatiorBy_,   
                                  rules: [{
                                    whitespace: true, message: '请选择盘点人',
                                  }]
                            })(
                                <Select
                                      showSearch
                                      placeholder="选择盘点人"
                                      optionFilterProp="children"  
                                  >
                                      {getUser(userList)}
                                  </Select>   
                                )}
                          </FormItem> ):null} 
                        </Col>
                        <Col span={12}>
                          <FormItem
                            {...formItemLayout}
                            label="重复周期"
                          >
                                <RadioGroup value={cycletime.cycleType} onChange={cycletimeChange}>
                                  <Radio value={1}>每天</Radio>
                                  <Radio value={2}>每周</Radio>
                                  <Radio value={3}>每月</Radio>
                                </RadioGroup>
                          </FormItem>    
                      </Col>
                      </Row>
                        <FormItem
                            {...formItemLayout1}
                            required
                            label="盘点时间"
                            >                          
                            {showIns(cycletime)}
                            <div>
                              <Button type="primary" size="large" onClick={addIns}>添加时间</Button>
                            </div>
                        </FormItem>
                      <Row>
                        <Col span={24}>
                        <FormItem
                          {...formItemLayout1}
                          label="所在机房"
                          hasFeedback
                        >
                            {getFieldDecorator('roomId', {
                              initialValue: typeof(item.roomId_)=="undefined" ? undefined : item.roomId_ + '',
                                rules: [{
                                  required: true, whitespace: true, message: '请选择机房',
                                }]
                            })(
                                <Select
                                    showSearch
                                    placeholder="选择机房"
                                    optionFilterProp="children"  
                                    onChange={this.handleRoomChange}
                                >
                                    {getRoom(roomList)}
                                </Select>     
                            )}
                         </FormItem>
                        </Col>
                      </Row>

                      <Row>                        
                        <Col span={24}>
                           <FormItem
                              {...formItemLayout1}
                              label="盘点机柜"
                              hasFeedback
                            >
                            {getFieldDecorator('rackIds', {
                                initialValue: item.rackIdsString,
                                rules: [{
                                  required: true, type:'array', whitespace: true, message: '请选择盘点机柜',
                                }]
                           })(
                               <TreeSelect
                                showSearch
                                treeCheckable
                                multiple
                                treeNodeFilterProp="title"
                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                placeholder="请选择盘点机柜"
                                notFoundContent="无匹配结果"
                                allowClear
                                treeData={treeData(rackList)}
                                treeDefaultExpandAll
                              >                              
                              </TreeSelect>
                              )}
                        </FormItem> 
                        </Col>
                      </Row>
                         {/* <FormItem
                            {...formItemLayout}
                              label="开始时间"
                              hasFeedback
                            >

                             {getFieldDecorator('beginTime', {
                                initialValue: moment(item.beginTime),   
                                rules: [{
                                  required: true, type: 'object',whitespace: true, message: '请选择开始时间',
                                 }]
                               })(
                                <DatePicker showTime={{ format: 'HH:mm' }} format="YYYY-MM-DD HH:mm:ss" style={{width:'300px'}}/>
                              )}
                        </FormItem>  */}
                                            
                        <FormItem
                              {...formItemLayout1}
                              label="备注"
                              hasFeedback
                        >
                          {
                            getFieldDecorator('remark', {
                              initialValue:  item.remark,  
                              rules: [{ max: 200, message: '备注信息 200 字符以内' },]
                            })(<Input type="textarea" autosize={{ minRows: 3, maxRows: 6 }}/>)
                          }
                        </FormItem>     
                   
                </Form>              
        </Modal>        
      </span>
    );
  }
    
}

export default Form.create()(AddInventoryModal)